package channelService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"go-fox-edge-channel-serial/channelEntity"
)

type publishService struct {
}

func (e *publishService) publish(channelEntity *channelEntity.SerialChannelEntity, requestVO *commRedisRpc.ChannelRequestVO) error {
	if requestVO.Send == nil || requestVO.Send == "" {
		return errors.New("发送数据不能为空！")
	}
	if requestVO.Timeout == 0 {
		return errors.New("超时参数不能为空！")
	}
	if requestVO.Timeout > 10*1000 {
		return errors.New("超时参数不能大于10秒！")
	}

	if !channelEntity.Config.FullDuplex {
		return errors.New("半双工模式，不允许进行单向操作:" + requestVO.Name)
	}

	// 检查串口
	if channelEntity.SerialPort == nil {
		return errors.New("串口不存在或者未打开！")
	}

	// 格式转换
	send := Hex.DecodeString(requestVO.Send)

	cnt, err := channelEntity.SerialPort.Write(send)
	if err != nil {
		return err
	}
	if cnt == 0 {
		return errors.New("发送失败")
	}

	return nil
}
